<template>
  <div class="payOrder">
    <topBg :my-bg="'home/payOrder/bg.png'"></topBg>
    <div class="addressCard">
      <div class="top acenter" :class="{ isSelectRight: currentSelect == 1 }">
        <div
          class="topExpress ccenter"
          :class="{ greenLeft: currentSelect == 1 }"
          @click="selectExpress"
        >
          快递配送
        </div>
        <div
          class="topSelf ccenter"
          :class="{ whiteRight: currentSelect == 1 }"
          @click="selectSelf"
        >
          自提点自提
        </div>
      </div>

      <div v-show="currentSelect == 1">
        <div class="center jscenter" @click="showAddressDialog">
          <nut-image
            :src="getAssetsFile('home/payOrder/location.png')"
          ></nut-image>
          <div class="centerRight" v-if="selfAddress.phone">
            <div class="hasAddress">
              <p class="title">
                <span>自提点：</span>{{ selfAddress.place_name }}
              </p>
              <div class="acenter">
                <p class="name">{{ selfAddress.contact_person }}</p>
                <p class="phone">{{ selfAddress.phone }}</p>
              </div>
              <p class="addressDetail">{{ selfAddress.detail_address }}</p>
            </div>
          </div>
          <div class="noAddress" v-else>请选择自提点</div>
          <nut-image
            :src="getAssetsFile('home/payOrder/rightArrow.png')"
          ></nut-image>
        </div>
      </div>

      <div v-show="currentSelect == 0">
        <div class="center jscenter" @click="showAddressDialog">
          <nut-image
            :src="getAssetsFile('home/payOrder/location.png')"
          ></nut-image>

          <div class="centerRight" v-if="expressAddress.phone">
            <div class="hasAddress">
              <p class="title">{{ expressAddress.detail }}</p>
              <p class="name">{{ expressAddress.receiver }}</p>
              <p class="phone">{{ expressAddress.phone }}</p>
            </div>
          </div>
          <div class="noAddress" v-else>请选择收货地址</div>
          <nut-image
            :src="getAssetsFile('home/payOrder/rightArrow.png')"
          ></nut-image>
        </div>
      </div>
    </div>

    <div class="otherAddress" v-if="currentSelect == 1">
      <p>团长还希望你完成以下信息</p>
      <div class="otherCenter jscenter" @click="showOther">
        <nut-image
          :src="getAssetsFile('home/payOrder/defaultUser.png')"
        ></nut-image>
        <div class="centerRight" v-if="expressAddress.phone">
          <div class="hasAddress">
            <p class="title">{{ expressAddress.detail }}</p>
            <p class="name">{{ expressAddress.receiver }}</p>
            <p class="phone">{{ expressAddress.phone }}</p>
          </div>
        </div>
        <div class="noAddress" v-else>请选择收货地址</div>
        <nut-image
          :src="getAssetsFile('home/payOrder/rightArrow.png')"
        ></nut-image>
      </div>
    </div>

    <div class="orderList">
      <div class="orderGoods">
        <div
          class="orderItem"
          v-for="(father, index) in receptData.list"
          :key="index"
        >
          <div class="orderUser jscenter">
            <nut-image class="userIcon" round :src="father.avatar" showError>
              <template #error>
                <nut-image
                  src="https://google-quanjing-game.oss-cn-hangzhou.aliyuncs.com/chenxing/avatar.png"
                  fit="contain"
                />
              </template>
            </nut-image>
            <p class="name">{{ father.nickname }}</p>
            <p class="info texthiden">{{ father.title }}</p>
            <nut-image
              :src="getAssetsFile('home/payOrder/rightArrow.png')"
            ></nut-image>
          </div>
          <template v-for="child in father.cart_items" :key="child.id">
            <ProductCard
              :options="child"
              @plus="plusCount(child)"
              @reduce="reduceCount(child, father)"
              @show="showFn"
            ></ProductCard
          ></template>
        </div>
        <div class="orderMark jscenter">
          <nut-input
            style="padding: 0; border: none"
            label="备注"
            type="text"
            placeholder="请输入您需要备注的内容"
            v-model="user_remark"
            max-length="100"
          />
          <nut-image
            :src="getAssetsFile('home/payOrder/rightArrow.png')"
          ></nut-image>
        </div>
        <div class="orderPrice jscenter">
          <p>商品金额</p>
          <p class="totalPrice"><span>¥</span>{{ totalPrice }}</p>
        </div>
        <div class="orderBottom">
          <span class="orderCount"> 共{{ totalCount }}件</span>
          实际支付：
          <p><span class="character">¥</span>{{ totalPrice }}</p>
        </div>
      </div>
    </div>

    <!-- <div class="payType">
      <div class="payItem jscenter" v-for="pay in payList" :key="pay.id">
        <nut-image class="useIcon" :src="getAssetsFile(pay.img)"></nut-image>
        <p>{{ pay.name }}</p>
        <nut-image
          v-if="currentPay == pay.id"
          class="hasChose"
          :src="getAssetsFile('home/payOrder/chosePay.png')"
        ></nut-image>
        <nut-image
          v-else
          class="noChose"
          :src="getAssetsFile('home/payOrder/noChose.png')"
          @click="chosePay(pay)"
        ></nut-image>
      </div>
    </div> -->

    <div class="orderBtn">
      <p>共{{ totalCount }}件</p>
      <div class="total">
        合计：
        <p><span>¥</span>{{ totalPrice }}</p>
      </div>
      <div class="buttonSmall ccenter" @click="createOrder">
        <nut-image
          class="orderClick"
          :src="getAssetsFile('home/payOrder/greenBtn.png')"
        ></nut-image>
        <p>提交订单</p>
      </div>
    </div>

    <commonDialog ref="noticeRef" @confirm="submitOrder" @cancel="cancelOrder">
      <template #title>
        <p class="notice">通知</p>
      </template>
      <p class="dialogtitle">下列订单不支持退货退款</p>
      <div class="dialogGoods">
        <template v-if="receptData.list?.length > 0">
          <div
            class="goodsItem"
            v-for="goods in receptData.list[0].cart_items"
            :key="goods.id"
          >
            <div class="goodsLeft">
              <p class="goodsTitle texthiden">{{ goods.goods_name }}</p>
              <p class="goodsInfo">规格:{{ goods.goods_spec }}</p>
            </div>
            <div class="goodsCount">共{{ goods.quantity }}件</div>
          </div></template
        >
      </div>
    </commonDialog>

    <commonDialog ref="cancelPayRef">
      <template #title>
        <p class="cancelNotice">真的要放弃付款么</p>
      </template>
      <p class="cancelContent ccenter">
        订单将在<span
          ><nut-countdown :end-time="defaultEndTime.end"></nut-countdown></span
        >后自动关闭
      </p>
      <template #cancel> 残忍放弃</template>
      <template #confirm> 继续付款</template>
    </commonDialog>

    <commonDialog ref="successRef" :btnCount="1" @confirm="goTopage">
      <div class="successContent">
        <nut-image
          class="successIcon"
          :src="getAssetsFile('home/payOrder/successIcon.png')"
        ></nut-image>
        <p class="successTitle">恭喜跟团成功</p>
      </div>
    </commonDialog>

    <addressPopup
      ref="addressDialog"
      :options="addressData"
      @save="saveAdress"
      @add="addNewAddress"
    ></addressPopup>

    <my-image-preview ref="myImagePreviewRef"></my-image-preview>
  </div>
</template>

<script setup lang="ts">
import { removePayStatus, getPayStatus } from "@/utils/auth";
import { getAssetsFile, isRes } from "@/utils/pub-use";
import topBg from "../components/topBg/topBg.vue";
import ProductCard from "@/components/productCard/ProductCard.vue";
import { Toast } from "@nutui/nutui";
import { ref, reactive, onMounted } from "vue";
import commonDialog from "@/components/Dialog/index.vue";
import { useRoute, useRouter } from "vue-router";
import { getListApi, updateCarApi } from "@/api/car/index";
import {
  createOrderApi,
  getaddressListApi,
  selfPrimingListApi,
} from "@/api/pay/index";
import useCommonStore from "@/store/common";
import addressPopup from "@/components/addressPopup/index.vue";
import myImagePreview from "@/components/imagePreview/index.vue";
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;
const myImagePreviewRef = ref<InstanceType<typeof myImagePreview>>();

const showFn = (url: string) => {
  myImagePreviewRef.value?.showFn(url);
};
const commonStore = useCommonStore();
//获取页面id
const route = useRoute();
const router = useRouter();

let getListParam = {
  page: 1,
  pagesize: 9999,
  item_ids: "",
};
const getList = async () => {
  if (getPayStatus()) {
    removePayStatus();
  }
  if (JSON.parse(localStorage.getItem("car_ids") || "[]").length) {
    getListParam.item_ids = JSON.parse(localStorage.getItem("car_ids") || "[]");
  }
  let res = await getListApi(getListParam);
  if (isRes(res)) {
    receptData.value = res.result;

    receptData.value.isChose = false;
    receptData.value.list.map((item: any, index: number) => {
      item.isChose = false;
      item.cart_items.map((element: any, location: number) => {
        element.isChose = false;
      });
    });
    getTotalCount();
    getTotalPrice();
  }
};

getList();
let selfAddress: any = ref("");
let expressAddress: any = ref("");
const selfPrimingList = async () => {
  let res = await selfPrimingListApi({
    page: 1,
    pagesize: 9999,
    groupbuy_id: route.query.groupbuy_id,
  });
  if (isRes(res)) {
    addressData.value = res.result;
    addressData.value.myTitle = "自提点";
    addressDialog.value?.openDialog();
  }
};
const getaddressList = async () => {
  let res = await getaddressListApi({ page: 1, pagesize: 9999 });
  if (isRes(res)) {
    addressData.value = res.result;
    addressData.value.myTitle = "快递配送";
    addressDialog.value?.openDialog();
  }
};

//获取购物车信息
let receptData: any = ref({});
//--------------------------------------------支付方式选择--------------------------------------------
const payList = [
  { id: 1, img: "home/payOrder/wxPay.png", name: "微信支付" },
  { id: 2, img: "home/payOrder/aliPay.png", name: "支付宝" },
];
let currentPay = ref<number>(1);
const chosePay = (item: any) => {
  currentPay.value = item.id;
};
//--------------------------------------------快递自提选项卡--------------------------------------------
let currentSelect = ref<number>(0);

let logistics_type: any = route.query.logistics_type;
const getTab = () => {
  if (logistics_type == 1) {
    currentSelect.value = 0;
  } else if (logistics_type == 2) {
    currentSelect.value = 1;
  }
};

getTab();

const selectExpress = () => {
  if (logistics_type == 1 || logistics_type == 3) {
    currentSelect.value = 0;
  }
};
const selectSelf = () => {
  if (logistics_type == 2 || logistics_type == 3) {
    currentSelect.value = 1;
  }
};

//计算值
let totalPrice = ref<number>(0);
let totalCount = ref<number>(0);
const getTotalCount = () => {
  totalCount.value = 0;
  receptData.value.list.map((item: any) => {
    item.cart_items.map((element: any) => {
      totalCount.value = totalCount.value + element.quantity;
    });
  });
};
const getTotalPrice = () => {
  totalPrice.value = 0;
  receptData.value.list.map((item: any) => {
    item.cart_items.map((element: any) => {
      totalPrice.value =
        (element.format_price * 100 * element.quantity +
          totalPrice.value * 100) /
        100;
    });
  });
};

const plusCount = async (item: any) => {
  let param = {
    item_id: item.id,
    quantity: 1,
  };
  let res = await updateCarApi(param);
  if (isRes(res)) {
    item.quantity++;
    getTotalPrice();
    getTotalCount();
  }
};

const reduceCount = async (item: any, father: any) => {
  let param = {
    item_id: item.id,
    quantity: -1,
  };
  let res = await updateCarApi(param);
  if (isRes(res)) {
    item.quantity--;
    if (item.quantity == 0) {
      father.cart_items.map((cData: any, index: number) => {
        if (cData.id == item.id) {
          father.cart_items.splice(index, 1);
        }
      });
    }
    getTotalCount();
    getTotalPrice();
  }
};

//--------------------------------------------打开提示弹窗--------------------------------------------
const noticeRef = ref<InstanceType<typeof commonDialog>>();
const showDialog = () => {
  noticeRef.value?.openDialog();
};

const submitOrder = async () => {
  canClickSubmit = false;
  let goods_list: any = [];
  receptData.value.list.map((father: any, index: number) => {
    father.cart_items.map((child: any, location: number) => {
      let temp = {
        goods_id: child.goods_id,
        spec_combination_id: child.spec_combination_id,
        quantity: child.quantity,
      };
      goods_list.push(temp);
    });
  });

  let body: any = {
    groupbuy_id: Number(route.query.groupbuy_id || ""),
    self_priming_id: currentSelect.value == 1 ? selfAddress.value.id : "",
    logistics_type: currentSelect.value + 1,
    user_remark: user_remark.value,
    total_money: totalPrice.value,
    rec_name: expressAddress.value.receiver,
    rec_phone: expressAddress.value.phone,
    rec_location: expressAddress.value.city_province,
    rec_address: expressAddress.value.detail,
    goods_list: goods_list,
  };
  let res = await createOrderApi(body);
  if (isRes(res)) {
    proxy.$cxpay.startPayment(
      res.result.payorder_no,
      res.result.total_fee,
      res.result.order_body,
      "城信余额支付",
      "chengxinPaycallback"
    );
  }
};
const cancelOrder = () => {
  noticeRef.value?.closeDialog();
};

//--------------------------------------------打开放弃付款弹窗--------------------------------------------
const cancelPayRef = ref<InstanceType<typeof commonDialog>>();
const defaultEndTime = reactive({
  end: Date.now(),
});
const showCancelPayDialog = () => {
  defaultEndTime.end = Date.now() + 60 * 10000;
  cancelPayRef.value?.openDialog();
};

//--------------------------------------------购买成功弹窗--------------------------------------------
const successRef = ref<InstanceType<typeof commonDialog>>();
const showSuccessDialog = () => {
  successRef.value?.openDialog();
};

//
let addressData: any = ref({});
const addressDialog = ref<InstanceType<typeof addressPopup>>();
const showAddressDialog = () => {
  if (currentSelect.value == 1) {
    selfPrimingList();
  } else {
    getaddressList();
  }
};
let showOtherFlag = false;
const showOther = () => {
  showOtherFlag = true;
  getaddressList();
};

const saveAdress = (payload: any) => {
  if (showOtherFlag) {
    expressAddress.value = payload;
  } else {
    if (currentSelect.value == 1) {
      selfAddress.value = payload;
    } else {
      expressAddress.value = payload;
    }
  }
  showOtherFlag = false;
  addressDialog.value?.closeDialog();
};

const addNewAddress = (payload: any) => {
  if (payload.myTitle == "快递配送") {
    router.push({
      path: "/address",
      query: {
        needBack: 1,
      },
    });
  }
};
let user_remark: any = ref("");
let canClickSubmit = true;
const createOrder = async () => {
  if (canClickSubmit) {
    if (!expressAddress.value) {
      Toast.warn("请选择收货地址");
    } else if (currentSelect.value == 1 && !selfAddress.value) {
      Toast.warn("请选择自提点");
    } else {
      if (receptData.value.list[0]?.is_allowed_refund == 0) {
        showDialog();
      } else {
        submitOrder();
      }
    }
  }
};

onMounted(() => {
  window.addEventListener("setItem", (e) => {
    canClickSubmit = true;
    let newV = sessionStorage.getItem("pay_status");
    if (newV == "CANCEL" || newV == "FAIL") {
      router.push("/order");
    } else if (newV == "SUCCESS") {
      showSuccessDialog();
    }
  });
});
const goTopage = () => {
  router.push("/home");
};
</script>

<style lang="scss" scoped>
.payOrder {
  background: #f8f9fa;
  padding-bottom: 229px;
  .addressCard {
    position: relative;
    margin: 0 20px;
    margin-top: -256px;
    border-radius: 20px;

    .top {
      background: url("../../../assets/home/payOrder/bigLeft.png");
      background-size: cover;
      height: 82px;
      .topExpress {
        flex: 1;
        font-size: 32px;
        font-weight: 500;
        color: #000000;
      }
      .greenLeft {
        margin-top: 15px;
        font-size: 26px;
        color: #444d43;
      }
      .topSelf {
        margin-top: 15px;
        flex: 1;
        font-size: 26px;
        color: #444d43;
      }
      .whiteRight {
        font-size: 32px;
        font-weight: 500;
        color: #000000;
        margin-top: 0;
      }
    }
    .isSelectRight {
      background: url("../../../assets/home/payOrder/bigRight.png");
      background-size: cover;
    }
    .center {
      padding: 30px 20px;
      background: #ffffff;
      border-bottom-left-radius: 20px;
      border-bottom-right-radius: 20px;
      margin-top: -1px;
      .nut-image {
        :deep(img) {
          width: 25px;
          height: 30px;
        }
      }
      .centerRight {
        .hasAddress {
          .title {
            width: 550px;
            font-size: 30px;
            font-weight: 500;
            color: #000000;
          }
          .name {
            color: #666666;
            font-size: 26px;
            margin: 10px 0;
          }
          .phone {
            color: #666666;
            font-size: 26px;
          }
          .addressDetail {
            color: #666666;
            font-size: 26px;
            width: 500px;
          }
        }
      }
      .noAddress {
        color: #666666;
        font-size: 30px;
        margin-left: 24px;
        margin-right: auto;
      }
    }
  }
  .otherAddress {
    background: #ffffff;
    border-radius: 20px;
    padding: 24px 20px;
    border-radius: 20px;
    margin: 0 20px;
    margin-top: 20px;
    p {
      font-weight: 500;
      font-size: 28px;
    }
    .otherCenter {
      margin-top: 23px;
      .nut-image {
        margin-right: 24px;
        :deep(img) {
          width: 25px;
          height: 30px;
        }
      }
      .nut-image:last-child {
        margin-right: 0;
      }
      .centerRight {
        .hasAddress {
          .title {
            width: 550px;
            font-size: 30px;
            font-weight: 500;
            color: #000000;
          }
          .name {
            color: #666666;
            font-size: 26px;
            margin: 10px 0;
          }
          .phone {
            color: #666666;
            font-size: 26px;
          }
        }
      }
      .noAddress {
        color: #666666;
        font-size: 30px;
        margin-right: auto;
      }
      .nut-image {
        // margin-right: 24px;
        :deep(img) {
          width: 25px;
          height: 30px;
        }
      }
    }
  }

  .orderList {
    background: #ffffff;
    padding: 24px 20px;
    border-radius: 20px;
    margin: 0 20px;
    margin-top: 20px;
    .orderGoods {
      .orderMark {
        padding: 30px 0;
        border-bottom: 1px solid #eeeeee;
        p {
          color: #000000;
          font-size: 28px;
        }
        input {
          margin-left: auto;
          margin-right: 5px;
          width: 308px;
          height: 40px;
          background: none;
          outline: none;
          border: none;
          color: #000000;
          font-size: 28px;
          text-align: right;
        }
      }
      .orderPrice {
        padding: 30px 0;
        border-bottom: 1px solid #eeeeee;
        p {
          color: #000000;
          font-size: 28px;
        }
        .totalPrice {
          font-size: 18px;
          color: #000000;
          span {
            font-size: 15px;
          }
        }
      }
      .orderBottom {
        padding: 30px 0;
        font-size: 26px;
        color: #666666;
        display: flex;
        justify-content: flex-end;
        .orderCount {
          margin-right: 20px;
        }
        p {
          color: #f55726;
          font-weight: 500;
          margin-left: 5px;
        }
        .character {
          font-size: 22px;
        }
      }
    }
    .orderUser {
      .userIcon {
        margin: 0;
        :deep(img) {
          width: 50px;
          height: 50px;
        }
      }
      .name {
        font-size: 28px;
        color: #000000;
        margin-left: 10px;
        word-break: keep-all;
      }
      .info {
        text-align: right;
        font-size: 28px;
        color: #000000;
        margin-left: auto;
        width: 224px;
      }
    }
    .nut-image {
      margin-left: 4px;
      :deep(img) {
        width: 25px;
        height: 30px;
      }
    }
  }

  .payType {
    background: #ffffff;
    padding: 24px 20px;
    border-radius: 20px;
    margin: 0 20px;
    margin-top: 20px;
    .payItem {
      margin-top: 56px;
      .useIcon {
        width: 54px;
        height: 54px;
      }
      p {
        font-size: 30px;
        color: #000000;
        margin-left: 21px;
        margin-right: auto;
      }
      .hasChose,
      .noChose {
        width: 36px;
        height: 36px;
      }
    }
    .payItem:first-child {
      margin-top: 0;
    }
  }

  .orderBtn {
    position: fixed;
    bottom: 0;
    z-index: 2000;
    margin-top: 48px;
    height: 112px;
    background: #ffffff;
    padding: 10px 30px 10px 53px;
    width: -webkit-fill-available;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    p {
      color: #999999;
      font-size: 24px;
    }
    .total {
      display: flex;
      align-items: flex-end;
      color: #000000;
      font-size: 28px;
      margin-left: 13px;
      p {
        color: #f55726;
        font-size: 28px;
        span {
          font-size: 24px;
        }
      }
    }
    .buttonSmall {
      position: relative;
      margin-left: 20px;
      .orderClick {
        width: 200px;
        height: 80px;
      }
      p {
        position: absolute;
        color: #ffffff;
        font-weight: 500;
        font-size: 30px;
      }
    }
  }

  .nut-dialog {
    .notice {
      font-weight: 500;
      font-size: 36px;
      color: #000000;
      margin-top: 36px;
      margin-bottom: 34px;
    }
    .dialogtitle {
      font-size: 30px;
      color: #000000;
      text-align: left;
      padding: 0 30px;
    }
    .dialogGoods {
      margin-top: 30px;
      box-sizing: border-box;
      padding: 0 30px 60px 30px;
      overflow-y: auto;
      .goodsItem {
        margin-top: 30px;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        .goodsLeft {
          max-width: 427px;
          .goodsTitle {
            text-align: left;
            width: 427px;
            font-size: 26px;
            color: #000000;
          }
          .goodsInfo {
            margin-top: 8px;
            text-align: left;
            line-height: 27px;
            color: #999999;
            font-size: 22px;
          }
        }
      }
      .goodsItem:nth-child(1) {
        margin-top: 0;
      }
    }
    .cancelNotice {
      font-weight: 500;
      font-size: 36px;
      color: #000000;
      margin: 36px 0 60px 0;
    }
    .cancelContent {
      font-size: 30px;
      color: #000000;
      margin-bottom: 90px;
      :deep(.nut-cd-block) {
        color: #f55726;
      }
    }
    .successContent {
      margin: 50px auto;
      .successIcon {
        margin: 0 auto;
        width: 106px;
        height: 106px;
      }
      .successTitle {
        margin-top: 26px;
        font-weight: 500;
        color: #000000;
        font-size: 36px;
      }
    }
  }
}
</style>
